<template>
  <view class="file-manager-container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="nav-left">
        <button class="back-btn" @tap="goBack">
          <text class="icon">←</text>
        </button>
        <text class="title">文件管理</text>
      </view>
      <view class="nav-right">
        <button class="refresh-btn" @tap="refreshFiles">
          <text class="icon">🔄</text>
        </button>
      </view>
    </view>

    <!-- 文件统计信息 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-number">{{ fileList.length }}</text>
        <text class="stat-label">总文件数</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ totalSize }}</text>
        <text class="stat-label">总大小</text>
      </view>
    </view>

    <!-- 文件列表 -->
    <scroll-view 
      class="file-list" 
      scroll-y 
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMoreFiles"
    >
      <view v-if="fileList.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">📁</text>
        <text class="empty-text">暂无上传文件</text>
        <text class="empty-subtitle">上传的文件将在这里显示</text>
        <button class="refresh-empty-btn" @tap="refreshFiles">
          <text class="icon">🔄</text>
          <text>点击刷新</text>
        </button>
      </view>

      <view v-else>
        <view v-for="(file, index) in fileList" :key="index" class="file-item">
          <view class="file-icon" :class="getFileTypeClass(file.type)">
            <text>{{ getFileIcon(file.type) }}</text>
          </view>
          <view class="file-info">
            <text class="file-name">{{ file.name }}</text>
            <text class="file-details">{{ formatFileSize(file.size) }} • {{ file.uploadTime }}</text>
          </view>
          <view class="file-actions">
            <button class="action-btn" @tap="viewFile(file)">
              <text class="icon">👁️</text>
            </button>
            <button class="action-btn" @tap="downloadFile(file)">
              <text class="icon">⬇️</text>
            </button>
            <button class="action-btn delete" @tap="deleteFile(file, index)">
              <text class="icon">🗑️</text>
            </button>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="batch-btn" @tap="selectAll" :class="{ active: allSelected }">
        <text>{{ allSelected ? '取消全选' : '全选' }}</text>
      </button>
      <button class="batch-btn delete" @tap="batchDelete" :disabled="selectedFiles.length === 0">
        <text>删除选中 ({{ selectedFiles.length }})</text>
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      selectedFiles: [],
      allSelected: false,
      loading: false,
      refreshing: false,
      hasMore: true,
      page: 1,
      pageSize: 20
    }
  },
  computed: {
    totalSize() {
      const total = this.fileList.reduce((sum, file) => sum + (file.size || 0), 0)
      return this.formatFileSize(total)
    }
  },
  onLoad() {
    this.loadFiles()
  },
  onShow() {
    // 页面显示时刷新文件列表
    this.refreshFiles()
  },
  onUnload() {
    // 页面卸载时确保关闭所有loading状态
    uni.hideLoading()
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 加载文件列表
    async loadFiles(reset = false) {
      if (this.loading) return
      
      this.loading = true
      
      if (reset) {
        this.page = 1
        this.fileList = []
      }

      try {
        // 模拟从服务器获取文件列表
        // 实际项目中这里应该是API调用
        // 添加延迟模拟网络请求
        await new Promise(resolve => setTimeout(resolve, 800))
        
        const mockFiles = this.getMockFiles()
        
        if (reset) {
          this.fileList = mockFiles
        } else {
          this.fileList = [...this.fileList, ...mockFiles]
        }
        
        this.hasMore = mockFiles.length >= this.pageSize
        this.page++
        
      } catch (error) {
        console.error('加载文件列表失败:', error)
        // 确保错误被正确传递，让上层调用者处理
        throw error
      } finally {
        // 确保loading状态总是被重置
        this.loading = false
      }
    },

    // 下拉刷新
    async onRefresh() {
      if (this.refreshing) return
      
      this.refreshing = true
      try {
        await this.loadFiles(true)
      } catch (error) {
        console.error('下拉刷新失败:', error)
        if (getCurrentPages().length > 0) {
          uni.showToast({
            title: '刷新失败',
            icon: 'none',
            duration: 2000
          })
        }
      } finally {
        this.refreshing = false
      }
    },

    // 刷新文件列表
    async refreshFiles() {
      // 防止重复调用
      if (this.loading) return
      
      uni.showLoading({
        title: '刷新中...',
        mask: true
      })
      
      try {
        await this.loadFiles(true)
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        })
      } catch (error) {
        console.error('刷新文件列表失败:', error)
        uni.showToast({
          title: '刷新失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        // 确保在页面仍然存在时才调用hideLoading
        if (getCurrentPages().length > 0) {
          uni.hideLoading()
        }
      }
    },

    // 加载更多文件
    loadMoreFiles() {
      if (this.hasMore && !this.loading && this.fileList.length > 0) {
        this.loadFiles()
      }
    },

    // 获取文件类型对应的CSS类名
    getFileTypeClass(type) {
      const typeMap = {
        'image': 'image',
        'pdf': 'pdf',
        'doc': 'doc',
        'docx': 'doc',
        'txt': 'txt',
        'zip': 'zip'
      }
      return typeMap[type] || 'other'
    },

    // 获取文件图标
    getFileIcon(type) {
      const iconMap = {
        'image': '🖼️',
        'pdf': '📄',
        'doc': '📝',
        'docx': '📝',
        'txt': '📄',
        'zip': '📦'
      }
      return iconMap[type] || '📄'
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 查看文件
    viewFile(file) {
      uni.showToast({
        title: '查看文件: ' + file.name,
        icon: 'none'
      })
    },

    // 下载文件
    downloadFile(file) {
      uni.showToast({
        title: '下载文件: ' + file.name,
        icon: 'none'
      })
    },

    // 删除文件
    deleteFile(file, index) {
      uni.showModal({
        title: '删除文件',
        content: '确定要删除文件 "' + file.name + '" 吗？',
        success: (res) => {
          if (res.confirm) {
            this.fileList.splice(index, 1)
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    },

    // 全选/取消全选
    selectAll() {
      this.allSelected = !this.allSelected
      if (this.allSelected) {
        this.selectedFiles = [...this.fileList]
      } else {
        this.selectedFiles = []
      }
    },

    // 批量删除
    batchDelete() {
      if (this.selectedFiles.length === 0) return
      
      uni.showModal({
        title: '批量删除',
        content: `确定要删除选中的 ${this.selectedFiles.length} 个文件吗？`,
        success: (res) => {
          if (res.confirm) {
            this.fileList = this.fileList.filter(file => !this.selectedFiles.includes(file))
            this.selectedFiles = []
            this.allSelected = false
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    },

    // 模拟文件数据
    getMockFiles() {
      const types = ['image', 'pdf', 'doc', 'txt', 'zip']
      const names = [
        '项目文档', '会议记录', '设计稿', '需求分析', '测试报告',
        '产品说明', '技术方案', '用户手册', 'API文档', '部署指南'
      ]
      
      // 模拟总文件数为10个，超过10个就不返回数据
      const maxTotalFiles = 10
      const startIndex = (this.page - 1) * this.pageSize
      
      if (startIndex >= maxTotalFiles) {
        return [] // 没有更多数据
      }
      
      const remainingFiles = maxTotalFiles - startIndex
      const actualPageSize = Math.min(remainingFiles, this.pageSize)
      
      const files = []
      for (let i = 0; i < actualPageSize; i++) {
        const type = types[Math.floor(Math.random() * types.length)]
        const name = names[Math.floor(Math.random() * names.length)] + 
                    '_' + (startIndex + i) + '.' + type
        
        files.push({
          name: name,
          type: type,
          size: Math.floor(Math.random() * 10240000) + 1024,
          uploadTime: new Date(Date.now() - Math.random() * 7 * 24 * 3600 * 1000).toLocaleDateString()
        })
      }
      
      return files
    }
  }
}
</script>

<style scoped>
/* 文件管理器容器 */
.file-manager-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
  position: relative;
}

/* 顶部导航栏 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.nav-left {
  display: flex;
  align-items: center;
}

.back-btn,
.refresh-btn {
  background: transparent;
  border: none;
  color: white;
  font-size: 40rpx;
  padding: 10rpx;
  margin-right: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

/* 统计信息 */
.stats-section {
  display: flex;
  background: white;
  margin: 20rpx 20rpx 15rpx 20rpx;
  padding: 30rpx;
  border-radius: 15rpx;
  box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.1);
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #667eea;
}

.stat-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}

/* 文件列表 */
.file-list {
  flex: 1;
  padding: 0 0 100rpx 0;
  margin: 0;
  overflow-y: auto;
  max-height: 60vh;
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 2px;
  height: 2px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.15);
  border-radius: 1px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.25);
}

/* Firefox */
.file-list {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.15) transparent;
}

/* 文件列表滚动条 */
.file-list::-webkit-scrollbar {
  width: 2px;
}

.file-list::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.15);
  border-radius: 1px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 36rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.empty-subtitle {
  font-size: 28rpx;
  color: #999;
}

.refresh-empty-btn {
  display: flex;
  align-items: center;
  background: #667eea;
  color: white;
  border: none;
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  margin-top: 40rpx;
  font-size: 28rpx;
}

.refresh-empty-btn .icon {
  margin-right: 10rpx;
}

.file-item {
  display: flex;
  align-items: center;
  background: white;
  margin: 0 20rpx 15rpx 20rpx;
  padding: 20rpx;
  border-radius: 15rpx;
  box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.1);
}

.file-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  margin-right: 15rpx;
  flex-shrink: 0;
}

.file-icon.image {
  background: #e3f2fd;
  color: #1976d2;
}

.file-icon.pdf {
  background: #ffebee;
  color: #d32f2f;
}

.file-icon.doc {
  background: #e8f5e8;
  color: #388e3c;
}

.file-icon.txt {
  background: #fff3e0;
  color: #f57c00;
}

.file-icon.zip {
  background: #f3e5f5;
  color: #7b1fa2;
}

.file-icon.other {
  background: #f5f5f5;
  color: #757575;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-details {
  display: block;
  font-size: 24rpx;
  color: #999;
}

.file-actions {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  flex-shrink: 0;
}

.action-btn {
  background: transparent;
  border: none;
  font-size: 32rpx;
  padding: 8rpx;
  margin-left: 15rpx;
  color: #667eea;
}

.action-btn.delete {
  color: #f44336;
}

.action-btn:disabled {
  opacity: 0.5;
}

/* 底部操作栏 */
.bottom-actions {
  display: flex;
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.batch-btn {
  flex: 1;
  background: #f5f5f5;
  border: none;
  padding: 20rpx;
  margin: 0 10rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.batch-btn.active {
  background: #667eea;
  color: white;
}

.batch-btn.delete {
  background: #ffebee;
  color: #d32f2f;
}

.batch-btn:disabled {
  opacity: 0.5;
}

/* 移动端适配 */
@media screen and (max-width: 480px) {
  .file-item {
    padding: 20rpx;
  }
  
  .file-icon {
    width: 60rpx;
    height: 60rpx;
    font-size: 30rpx;
  }
  
  .file-name {
    font-size: 28rpx;
  }
  
  .file-details {
    font-size: 24rpx;
  }
}
</style>